package com.wxtwxt.ruralmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wxtwxt.ruralmall.common.constant.ProductConstant;
import com.wxtwxt.ruralmall.common.to.SkuEsModel;
import com.wxtwxt.ruralmall.common.to.SkuReductionTo;
import com.wxtwxt.ruralmall.common.to.SpuBoundsTo;
import com.wxtwxt.ruralmall.common.to.StockTo;
import com.wxtwxt.ruralmall.common.utils.R;
import com.wxtwxt.ruralmall.product.entity.*;
import com.wxtwxt.ruralmall.product.feign.CouponFeignService;
import com.wxtwxt.ruralmall.product.feign.SearchFeignService;
import com.wxtwxt.ruralmall.product.feign.WareFeignService;
import com.wxtwxt.ruralmall.product.service.*;
import com.wxtwxt.ruralmall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxtwxt.ruralmall.common.utils.PageUtils;
import com.wxtwxt.ruralmall.common.utils.Query;

import com.wxtwxt.ruralmall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private BrandService brandService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private AttrService attrService;
    @Resource
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(queryWrapper -> queryWrapper.eq("id", key).or().like("spu_name", key));
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", spuSaveVo.getDecript()));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        spuImagesService.saveImages(spuInfoEntity.getId(), spuSaveVo.getImages());
        productAttrValueService.saveProductAttrValue(spuInfoEntity.getId(), spuSaveVo.getBaseAttrs());
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        spuBoundsTo.setBuyBounds(bounds.getBuyBounds());
        spuBoundsTo.setGrowBounds(bounds.getGrowBounds());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }
        List<Skus> skusList = spuSaveVo.getSkus();
        if (skusList.size() > 0) {
            skusList.forEach(skus -> {
                String defaultImage = "";
                for (Images image : skus.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImage = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(skus, skuInfoEntity);
                skuInfoEntity.setSkuDesc(String.join(",", skus.getDescar()));
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                List<SkuImagesEntity> skuImagesEntities = skus.getImages().stream().map(sku -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(sku.getImgUrl());
                    skuImagesEntity.setDefaultImg(sku.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> StringUtils.isNotEmpty(entity.getImgUrl())).collect(Collectors.toList());
                skuImagesService.saveSkuImage(skuImagesEntities);
                List<Attr> attrList = skus.getAttr();
                if (attrList.size() > 0) {
                    List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrList.stream().map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                        BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveSkuSaleAttrValue(saleAttrValueEntities);
                    SkuReductionTo skuReductionTo = new SkuReductionTo();
                    BeanUtils.copyProperties(skus, skuReductionTo);
                    skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                    R result = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (result.getCode() != 0) {
                        log.error("远程保存spu积分信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void upBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkuBySpuId(spuId);
        List<ProductAttrValueEntity> list = productAttrValueService.getBaseListForSpu(spuId);
        List<Long> attrIds = list.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> hasSearchTypeIds = attrService.getSearchTypeId(attrIds);
        Set<Long> set = new HashSet<>(hasSearchTypeIds);
        List<SkuEsModel.Attrs> newList = list.stream().filter(entity -> set.contains(entity.getAttrId())).map(entity -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(entity, attrs);
            return attrs;
        }).collect(Collectors.toList());
        // TODO 优化
        // TODO 远程调用仓储服务获取是否有库存
        List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> stockMap = null;
        try {
            List<StockTo> stockTos = wareFeignService.stockIsExist(skuIdList);
            stockMap = stockTos.stream().collect(Collectors.toMap(StockTo::getSkuId, StockTo::getHasStock));
        }catch(Exception e) {
            log.error("库存服务调用异常：{}", e);
        }
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            skuEsModel.setSkuId(sku.getSkuId());
            skuEsModel.setSpuId(spuId);
            skuEsModel.setSkuTitle(sku.getSkuTitle());
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            skuEsModel.setSaleCount(sku.getSaleCount());
            skuEsModel.setHasScore(0L);
            if(finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            skuEsModel.setHasScore(0L);
            Long catalogId = sku.getCatalogId();
            skuEsModel.setCatalogId(catalogId);
            CategoryEntity category = categoryService.getById(catalogId);
            skuEsModel.setCatalogName(category.getName());
            Long brandId = sku.getBrandId();
            skuEsModel.setBrandId(brandId);
            BrandEntity brandEntity = brandService.getById(brandId);
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setAttrs(newList);
            return skuEsModel;
        }).collect(Collectors.toList());
        R r = searchFeignService.productStatusUp(skuEsModels);
        if(r.getCode() == 0) {
            UpdateWrapper<SpuInfoEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("publish_status", ProductConstant.productStatusEnum.SPU_UP.getCode());
            updateWrapper.set("update_time", new Date());
            updateWrapper.eq("id", spuId);
            this.update(updateWrapper);
        }else {
            // 远程调用失败
            // TODO 重复调用 接口幂等性 重试机制
        }
    }

}